import _ from "lodash";
import { formatTime } from "@/utils/date";

/**
 * 手机号脱敏
 * @param {*} mobileNumber
 * @returns
 */
export const maskMobileNumber = (mobileNumber) => {
  if (!mobileNumber) return "";
  return (
    mobileNumber.substr(0, 3) +
    "****" +
    mobileNumber.substr(mobileNumber.length - 4)
  );
};

/**
 * 姓名打星处理
 * @param name
 * @returns {*|string}
 */
export const maskRealName = (name) => {
  if (!name) return "";
  if (name.length === 1) return `${name}*`;
  if (name.length === 2) return `${name.substr(0, 1)}*`;
  return name.substr(0, 1) + "*" + name.substr(name.length - 1);
};

/**
 * 身份证脱敏
 * @param {*} idCardNumber
 * @returns
 */
export const maskIDCardNumber = (idCardNumber) => {
  if (!idCardNumber) return "";
  // 将身份证号码转换为字符串
  const idCardNumberString = idCardNumber.toString();
  return (
    idCardNumberString.substr(0, 4) +
    "****" +
    idCardNumberString.substr(idCardNumberString.length - 4)
  );
};

/**
 * 定时器
 * 使用setTimeout实现setInterval
 * @returns
 */
export const interval = (func, delay) => {
  let timer = null;
  let isCleared = false;

  const interFunc = function () {
    if (isCleared) return; // 检查定时器是否已经被清除
    func.call(null);
    timer = setTimeout(interFunc, delay); // 递归调用
  };

  timer = setTimeout(interFunc, delay); // 触发递归

  const clearTimer = () => {
    clearTimeout(timer);
    isCleared = true; // 标记定时器已被清除
    timer = null;
  };

  return {
    clearTimer,
  };
};

/**
 * 延迟执行
 * @param {*} time
 * @returns
 */
export const delay = (time = 300) => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time);
  });
};

/**
 * 节流
 * @param {*} func
 * @param {*} limit
 * @returns
 */
export const throttle = (func, limit) => {
  let inThrottle;
  return function () {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};

/**
 * 防抖
 * @param {*} func
 * @param {*} delay
 * @returns
 */
export const debounce = (func, delay) => {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func.apply(context, args);
    }, delay);
  };
};

/**
 * 转成保留俩位小数
 * @param {*} num
 * @returns
 */
export function convertMoney(num, figure = 100) {
  return parseFloat((num / figure).toFixed(2));
}

// 类型转换
export const convertType = (param, type) => {
  switch (type) {
    case "number":
      return Number(param);
    case "string":
      return String(param);
    case "boolean":
      if (typeof param === "string") {
        return param.toLowerCase() === "true";
      }
      return Boolean(param);
    case "date":
      return formatTime(param);
    case "array":
      if (!param) return [];
      // 如果是数组，直接返回
      if (Array.isArray(param)) {
        return param;
      }
      // 如果是字符串，尝试按逗号拆分
      if (typeof param === "string") {
        return param.includes(",")
          ? param.split(",").map(Number)
          : [Number(param)];
      }
      try {
        return JSON.parse(param);
      } catch {
        throw new Error("Invalid array format");
      }
    case "object":
      try {
        return typeof param === "object" ? param : JSON.parse(param);
      } catch {
        throw new Error("Invalid object format");
      }
    default:
      return param;
  }
};

// 批量参数对象转换类型
export const batchConvertType = (params, fieldTypeList) => {
  const newParams = { ...params };
  fieldTypeList.forEach((item) => {
    newParams[item.prop] = convertType(params[item.prop], item.type);
  });
  return newParams;
};

// 参数转换金额单位
export const convertMoneyUnit = (num, unit, decimals = 0) => {
  if (!_.isNil(decimals) || !_.isNaN(decimals)) {
    const result = convertType(num, "number") * unit;
    return convertType(result.toFixed(decimals), "number");
  }
  return 0;
};

// 批量参数对象转换金额单位
export const batchConvertMoneyUnit = (params, fieldList) => {
  const newParams = {};
  fieldList.forEach((item) => {
    newParams[item.prop] = convertMoneyUnit(
      params[item.prop],
      item.unit,
      item.decimals
    );
  });
  return newParams;
};

// 分转成元
export const getMoneyCentYuan = (money) => {
  return convertMoneyUnit(money, 0.01, 2);
};
// 元转成分
export const getMoneyYuanCent = (money) => {
  return convertMoneyUnit(money, 100, 0);
};
export const batchGetMoneyYuanCent = (params, fieldList) => {
  const newFieldList = fieldList.map((item) => ({
    prop: item,
    unit: 100,
  }));
  return batchConvertMoneyUnit(params, newFieldList);
};

// 生成uuid
export function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
    const random = (Math.random() * 16) | 0; // 生成 0-15 的随机数
    const value = char === "x" ? random : (random & 0x3) | 0x8; // 根据规则生成 'x' 或 'y'
    return value.toString(16); // 转换为十六进制
  });
}

// 打乱数组
export function shuffleArray(arr) {
  // 克隆数组，避免修改原数组
  const shuffledArray = [...arr];

  for (let i = shuffledArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1)); // 随机索引
    // 交换元素
    [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
  }

  return shuffledArray;
}
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: (e) => {
        let statusBarHeight = 0;
        let customBarHeight = 0;
        // #ifndef MP
        statusBarHeight = e.statusBarHeight;
        if (e.platform == "android") {
          customBarHeight = e.statusBarHeight + 50;
        } else {
          customBarHeight = e.statusBarHeight + 45;
        }
        // #endif

        // #ifdef MP-WEIXIN
        statusBarHeight = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        customBarHeight =
          custom.bottom +
          (custom.top - e.statusBarHeight <= 4
            ? custom.top - e.statusBarHeight + 4
            : custom.top - e.statusBarHeight);
        // #endif

        // #ifdef MP-ALIPAY
        statusBarHeight = e.statusBarHeight;
        customBarHeight = e.statusBarHeight + e.titleBarHeight;
        // #endif
        resolve({
          ...e,
          statusBarHeight,
          customBarHeight,
        });
      },
      fail: (err) => {
        console.log("获取设备信息失败", err);
        reject();
      },
    });
  });
};